package com.kjc.demo.netty.ieee754;

import java.math.BigDecimal;
import java.math.BigInteger;

import javax.xml.bind.annotation.adapters.HexBinaryAdapter;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class IEEE754 {
	
	/**
	  * 字节数组转IEEE 754
	  *
	  * @param bytes 长度4或者8
	  * @author: 若非
	  * @date: 2021/9/10 16:57
	  */
	 public static BigDecimal bytesToSingle(byte[] bytes) {
		 log.info(bytes.length + "");;
	  if (bytes.length > 8) {
	   throw new ArrayIndexOutOfBoundsException("转化失败，字节超出整型大小！");
	  }
	  String hex = new BigInteger(bytes).toString(16);
	  log.info(hex + "--" +new BigInteger(bytes));
	  return hexToSingle(hex, bytes.length * 8);
	 }
	 
	 /**
	  * 字节数组转IEEE 754
	  *
	  * @param hex
	  * @param bitLen 32或者64
	  * @author: 若非
	  * @date: 2021/9/10 16:57
	  */
	 private static BigDecimal hexToSingle(String hex, int bitLen) {
	  if (StrUtil.isEmpty(hex)) {
	   return BigDecimal.valueOf(0);
	  }
	  if (bitLen == 32) {
	   int i = Integer.parseInt(hex, 16);
	   log.info("i--------------" + i);
	   float v = Float.intBitsToFloat(i);
	   log.info("v--------------" + v);
	   return new BigDecimal(v);
	  }
	  if (bitLen == 64) {
	   long l = Long.parseLong(hex, 16);
	   double d = Double.longBitsToDouble(l);
	   return new BigDecimal(d);
	  }
	  return BigDecimal.valueOf(0);
	 }
	 
	 
	 public static void main(String[] args) {
		String hex = "4640E6B6";
		HexBinaryAdapter adapter = new HexBinaryAdapter();
		byte[] dataBytes = adapter.unmarshal(hex);
		BigDecimal num = bytesToSingle(dataBytes);
		System.out.println(num.toString());
	}
	
}
